package com.yxinmiracle.search.controller;

import com.yxinmiracle.search.feign.SkuFeign;
import entity.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * @version 1.0
 * @author： YxinMiracle
 * @date： 2021-08-14 10:15
 */

@Controller
@RequestMapping("/search")
public class SkuController {
    @Autowired
    private SkuFeign skuFeign;

    @GetMapping("list")
    public String search(@RequestParam Map<String, String> searchMap, Model model) {
        Map<String, Object> resultMap = skuFeign.search(searchMap);
        model.addAttribute("result", resultMap);
        model.addAttribute("searchMap", searchMap);

        String url = url(searchMap);
        model.addAttribute("url", url);
        Page page = new Page<>(
                Long.valueOf(resultMap.get("total").toString()),
                Integer.valueOf(resultMap.get("pageNum").toString()),
                Integer.valueOf(resultMap.get("pageSize").toString())
        );
        model.addAttribute("page", page);
        return "search";
    }

    private String url(Map<String, String> searchMap) {
        String url = "/search/list";
        if (searchMap != null) {
            url += "?";
            for (Map.Entry<String, String> stringStringEntry : searchMap.entrySet()) {
                String key = stringStringEntry.getKey();
                String value = stringStringEntry.getValue();
                if (key.equals("sortField") || key.equals("sortRule") || key.equals("pageNum")){
                    continue;
                }
                url = url + key + "=" + value +"&";
            }
            url = url.substring(0,url.length()-1);
        }
        return url;
    }
}
